package top.codedance.iotp.slave.service;

import top.codedance.iotp.slave.SlaveApplication;
import com.fazecast.jSerialComm.SerialPort;
import com.serotonin.modbus4j.serial.SerialPortWrapper;
import org.apache.log4j.Logger;

import java.io.InputStream;
import java.io.OutputStream;

public class SerialPortWrapperImpl implements SerialPortWrapper {

    private Logger logger = SlaveApplication.getLogger(SerialPortWrapperImpl.class);

    private int baudRate;
    private int dataBits;
    private int stopBits;
    private int parity;

    private SerialPort commPort;

    public SerialPortWrapperImpl(String portDescriptor, int baudRate, int dataBits, int stopBits, int parity) {
        this.baudRate = baudRate;
        this.dataBits = dataBits;
        this.stopBits = stopBits;
        this.parity = parity;

        this.commPort = SerialPort.getCommPort(portDescriptor);
        this.commPort.setComPortParameters(this.baudRate, this.dataBits, this.stopBits, this.parity);
    }

    public boolean isOpen(){
        return this.commPort.isOpen();
    }

    @Override
    public void close() throws Exception {
        this.commPort.closePort();
    }

    @Override
    public void open() throws Exception {
        this.commPort.openPort(0, 1024*1024*2, 1024*1024*2);
    }

    @Override
    public InputStream getInputStream() {
        return this.commPort.getInputStream();
    }

    @Override
    public OutputStream getOutputStream() {
        return this.commPort.getOutputStream();
    }

    @Override
    public int getBaudRate() {
        return this.baudRate;
    }

    @Override
    public int getDataBits() {
        return this.dataBits;
    }

    @Override
    public int getStopBits() {
        return this.stopBits;
    }

    @Override
    public int getParity() {
        return this.parity;
    }
}
